package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetMealController {

    @Reference
    SetmealService setmealService;

    @Autowired
    JedisPool jedisPool;

    /**
     * 文件上传到七牛云
     */
    @RequestMapping("/upload")
    public Result upload(MultipartFile imgFile){
        try {
            //生成一个唯一的文件
            String uuid = UUID.randomUUID().toString().replace("-", "");

            //获取文件原始名称，截取后缀名
            String originalFilename = imgFile.getOriginalFilename();
            String extendName = originalFilename.substring(originalFilename.lastIndexOf("."));

            //拼接成一个新的文件名称
            String serverName = uuid + extendName;

            //上传文件到七牛
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),serverName);

            //执行到此说明文件已经上传成功了，只需要存储到Redis中
            /**
             * 参数1： set集合的名称
             * 参数2： 图片的名称
             */
            jedisPool.getResource().sadd(RedisConst.SETMEAL_PIC_RESOURCES,serverName);

            return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,serverName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }

    }

    /**
     * 添加套餐
     */
    @RequestMapping("/add")
    @PreAuthorize("hasAuthority('SETMEAL_ADD')")
    public Result add(Integer[] checkgroupIds,@RequestBody Setmeal setmeal){
        try {
            setmealService.add(checkgroupIds,setmeal);
            return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SETMEAL_FAIL);
        }

    }

    /**
     * 分页查询套餐
     */
    @RequestMapping("/findPage")
    @PreAuthorize("hasAuthority('SETMEAL_QUERY')")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return setmealService.findPage(queryPageBean);
    }


}
